package org.finesys.ai.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.finesys.ai.convert.AigcModelConvert;
import org.finesys.ai.entity.AigcModel;
import org.finesys.ai.mapper.AigcModelMapper;
import org.finesys.ai.service.AigcModelService;
import org.finesys.ai.vo.AigcModelExcelVO;
import org.finesys.chat.core.base.constants.EventTypeEnum;
import org.finesys.chat.core.base.events.AigcModelEvent;
import org.finesys.common.core.util.SpringContextHolder;
import org.finesys.common.mp.core.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class AigcModelSericeImpl extends BaseServiceImpl<AigcModelMapper, AigcModel> implements AigcModelService {


    @Override
    public boolean saveAigcModel(AigcModel aigcModel) {
        this.save(aigcModel);
        this.sendEvent(aigcModel, EventTypeEnum.ADD.getName());
        return true;
    }

    @Override
    public boolean updateAigcModel(AigcModel aigcModel) {
        this.updateById(aigcModel);
        this.sendEvent(aigcModel, EventTypeEnum.UPDATE.getName());
        return true;
    }

    @Override
    public boolean deleteAigcModelByIds(String[] ids) {
        if (ids == null || ids.length == 0) {
            return false;
        }
        List<AigcModel> list = this.listByIds(Arrays.asList(ids));
        list.stream().forEach(aigcModel -> {
            this.removeById(aigcModel);
            this.sendEvent(aigcModel, EventTypeEnum.DELETE.getName());
        });
        return true;
    }

    private void sendEvent(AigcModel aigcModel, String type) {
        AigcModelEvent event = new AigcModelEvent(aigcModel, type);
        boolean send = SpringContextHolder.publishEvent(event);
        if (!send) {
            if (log.isWarnEnabled()) {
                log.warn("发送模型事件[{}]失败", event);
            }
        }
    }

    @Override
    public List<AigcModelExcelVO> listExcel() {
        List<AigcModel> list = this.list();
        return AigcModelConvert.INSTANCE.convertList(list);
    }
}
